package com.ruoyi.web.controller.tool;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Random;

public class COSClientUtil {

    private final static String baseUrl = "https://user-casting-pic-1309892786.cos.ap-guangzhou.myqcloud.com";

    private final static String accessKey = "AKIDznMfiV3MQEm58uOdcNt98sNn6C2cw1pU";

    private final static String secretKey = "XnoY1DAqGQL0OVfdLnytXv2E9nBI9i12";

    private final static String regionName = "ap-guangzhou";

    private final static String bucketName = "user-casting-pic-1309892786";

    private final static String folderPrefix = "/mall-admin/";

    private static final COSCredentials credentials = new BasicCOSCredentials(accessKey,secretKey);
    // 配置 COS 区域 就购买时选择的区域 我这里是 广州（guangzhou）
    private static final ClientConfig clientConfig = new ClientConfig(new Region(regionName));

    /**
     * 上传文件
     *
     * @param file
     * @return
     * @throws Exception
     */
    public static String upload(MultipartFile file) throws IOException {
//        String m5d = CryptoUtil.SHA256(file.getInputStream());
        // 创建 COS 客户端连接
        COSClient cosClient = new COSClient(credentials,clientConfig);
        String fileName = file.getOriginalFilename();
        try {
            if (StringUtils.isBlank(fileName) || !fileName.contains(".")){
                fileName = "cropping"+System.currentTimeMillis()+".jpg";
            }
            String substring = fileName.substring(fileName.lastIndexOf("."));
            File localFile = File.createTempFile(String.valueOf(System.currentTimeMillis()),substring);
            file.transferTo(localFile);
            Random random = new Random();
            fileName =folderPrefix+random.nextInt(10000)+System.currentTimeMillis()+substring;
            // 将 文件上传至 COS
            PutObjectRequest objectRequest = new PutObjectRequest(bucketName,fileName,localFile);
            cosClient.putObject(objectRequest);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            cosClient.shutdown();
        }
        return baseUrl+fileName;

    }

}
